package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageInfo;
import com.ruoyi.system.domain.dto.DmsOutsideDto;
import com.ruoyi.system.domain.po.*;
import com.ruoyi.system.domain.vo.OutsideDto;
import com.ruoyi.system.domain.vo.OutsideVo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.OutsideService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class OutsideServiceImpl implements OutsideService {

    @Resource
    private DmsScreeningDetailMapper dmsScreeningDetailMapper;
    @Resource
    private DmsScreeningRecordMapper screeningRecordMapper;
    @Resource
    private DmsFirstAidMapper firstAidMapper;
    @Resource
    private DmsFirstAidValueMapper dmsFirstAidValueMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;

    @Override
    public void insertScreen(List<OutsideDto.DetailVo> detailVoList) {

        if (CollectionUtil.isNotEmpty(detailVoList)) {
            for (OutsideDto.DetailVo detailVo : detailVoList) {
                DmsScreeningDetail dmsScreeningDetail = BeanUtil.copyProperties(detailVo, DmsScreeningDetail.class);
                if (dmsScreeningDetailMapper.selectByPrimaryKey(detailVo.getId()) == null) {
                    List<OutsideDto.Record> recordList = detailVo.getRecordList();
                    if (CollectionUtil.isNotEmpty(recordList)) {
                        for (OutsideDto.Record record : recordList) {
                            DmsScreeningRecord dmsScreeningRecord = BeanUtil.copyProperties(record, DmsScreeningRecord.class);
                            dmsScreeningRecord.setId(IdUtil.getSnowflake().nextId());
                            dmsScreeningRecord.setQuestionnaireDetailId(dmsScreeningDetail.getId());
                            dmsScreeningRecord.setQuestionCode(record.getCode());
                            screeningRecordMapper.insertSelective(dmsScreeningRecord);

                            if ("SCWJ-idCard".equals(record.getCode())) {
                                dmsScreeningDetail.setIdcard(record.getAnswer());
                            }
                            if ("SCWJ-PHONE".equals(record.getCode())) {
                                dmsScreeningDetail.setPhone(record.getAnswer());
                            }
                        }
                    }
                    dmsScreeningDetailMapper.insertSelective(dmsScreeningDetail);
                }
            }
        }

    }

    @Override
    public void insertFirstAid(List<OutsideDto.Info> firstAidList) {
        if (CollectionUtil.isEmpty(firstAidList)) {
            for (OutsideDto.Info detailVo : firstAidList) {
                DmsFirstAid dmsFirstAid = BeanUtil.copyProperties(detailVo, DmsFirstAid.class);
                if (firstAidMapper.selectByPrimaryKey(dmsFirstAid.getId()) == null) {
                    firstAidMapper.insertSelective(dmsFirstAid);
                    List<OutsideDto.DetailRecord> detailRecordList = detailVo.getDetailRecordList();
                    if (CollectionUtil.isNotEmpty(detailRecordList)) {
                        for (OutsideDto.DetailRecord detailRecord : detailRecordList) {
                            List<OutsideDto.DetailRecordInfo> detailRecordInfoList = detailRecord.getDetailRecordInfoList();
                            if (CollectionUtil.isNotEmpty(detailRecordInfoList)) {
                                for (OutsideDto.DetailRecordInfo detailRecordInfo : detailRecordInfoList) {
                                    DmsFirstAidValue dmsFirstAidValue = BeanUtil.copyProperties(detailRecordInfo, DmsFirstAidValue.class);
                                    dmsFirstAidValue.setId(IdUtil.getSnowflake().nextId());
                                    dmsFirstAidValue.setStepId(detailVo.getId());
                                    dmsFirstAidValueMapper.insertSelective(dmsFirstAidValue);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public PageInfo<OutsideVo.DetailVo> query(DmsOutsideDto.Query dto) {

        DmsScreeningDetailExample dmsScreeningDetailExample = new DmsScreeningDetailExample();
        DmsScreeningDetailExample.Criteria criteria = dmsScreeningDetailExample.createCriteria();
        if (StrUtil.isNotEmpty(dto.getName())) {
            criteria.andNameLike("%" + dto.getName() + "%");
        }
        if (StrUtil.isNotEmpty(dto.getCounty())) {
            criteria.andCountyLike("%" + dto.getCounty() + "%");
        }
        if (StrUtil.isNotEmpty(dto.getPhone())) {
            criteria.andPhoneEqualTo(dto.getPhone());
        }
        if (StrUtil.isNotEmpty(dto.getIdCard())) {
            criteria.andIdcardEqualTo(dto.getIdCard());
        }
        if (StrUtil.isNotEmpty(dto.getCity())) {
            criteria.andCityLike("%" + dto.getCity() + "%");
        }
        if (dto.getRzscResult() != null) {
            criteria.andRzscResultEqualTo(dto.getRzscResult());
        }
        if (dto.getStartTime() != null) {
            criteria.andCreatedAtBetween(dto.getStartTime(), dto.getEndTime());
        }
        if (dto.getDangeStatus() != null) {
            criteria.andDangeStatusEqualTo(dto.getDangeStatus());
        }
        if (dto.getHospitalId() != null) {
            String s = sysDeptMapper.selectDeptNameByHospitalId(dto.getHospitalId());
            if (StrUtil.isNotEmpty(s)) {
                criteria.andHospitalNameEqualTo(s);
            }
        }
        List<DmsScreeningDetail> dmsScreeningDetails = dmsScreeningDetailMapper.selectByExample(dmsScreeningDetailExample);
        if (CollectionUtil.isNotEmpty(dmsScreeningDetails)) {
            List<OutsideVo.DetailVo> detailVos = BeanUtil.copyToList(dmsScreeningDetails, OutsideVo.DetailVo.class);
//            for (OutsideVo.DetailVo detailVo : detailVos) {
                for (OutsideVo.DetailVo vo : detailVos) {
                    DmsScreeningRecordExample dmsScreeningRecordExample = new DmsScreeningRecordExample();
                    dmsScreeningRecordExample.createCriteria().andRecStatusEqualTo((byte) 0).andQuestionnaireDetailIdEqualTo(vo.getId());
                    List<DmsScreeningRecord> dmsScreeningRecords = screeningRecordMapper.selectByExample(dmsScreeningRecordExample);
                    List<OutsideVo.DetailVo.Record> list = new ArrayList<>();
                    if (CollectionUtil.isNotEmpty(dmsScreeningRecords)) {
                        for (DmsScreeningRecord dmsScreeningRecord : dmsScreeningRecords) {
                            OutsideVo.DetailVo.Record record = new OutsideVo.DetailVo.Record();
                            record.setCode(dmsScreeningRecord.getQuestionCode());
                            record.setAnswer(dmsScreeningRecord.getAnswer());
                            list.add(record);
                        }
                        vo.setRecordList(list);
                    }
                }
//            }
            PageInfo<OutsideVo.DetailVo> detailVoPageInfo = new PageInfo<>(detailVos);
            PageInfo<DmsScreeningDetail> dmsScreeningDetailPageInfo = new PageInfo<>(dmsScreeningDetails);
            detailVoPageInfo.setTotal(dmsScreeningDetailPageInfo.getTotal());
            detailVoPageInfo.setPageNum(dmsScreeningDetailPageInfo.getPageNum());
            detailVoPageInfo.setPageSize(dmsScreeningDetailPageInfo.getPageSize());
            return detailVoPageInfo;
        }
        PageInfo<OutsideVo.DetailVo> result = new PageInfo<>();
        result.setList(new ArrayList<>());

        return result;
    }

    @Override
    public void exportRzScreen(HttpServletResponse response, DmsOutsideDto.Query param) {
        ExcelWriter excelWriter = ExcelUtil.getWriter();
        List<String> headerList = CollectionUtil.newArrayList(
                "姓名",
                "性别",
                "年龄",
                "身份证",
                "出生日期",
                "手机号",
                "判断力出现问题",
                "缺乏兴趣、爱好，活动减少了",
                "不断重复一件事",
                "学习使用某些日常工具或家用电器有困难",
                "记不清当前的月份或年份",
                "处理个人财务困难",
                "记不住和别人的约定",
                "日常记忆和思考能力出现问题",
                "筛查结果",
                "数据来源");
        excelWriter.writeHeadRow(headerList);

        PageInfo<OutsideVo.DetailVo> page = query(param);
        if (page != null) {
            List<OutsideVo.DetailVo> detailVos = page.getList();
            if (CollectionUtil.isNotEmpty(detailVos)) {
                int row = 0;
                for (int i = 0; i < detailVos.size(); i++) {
                    List<OutsideVo.DetailVo.Record> recordList = detailVos.get(i).getRecordList();
                    Map<String, OutsideVo.DetailVo.Record> map = new HashMap<>();
                    if (CollectionUtil.isNotEmpty(recordList)) {
                        map = recordList.stream().collect(Collectors.toMap(OutsideVo.DetailVo.Record::getCode, Function.identity()));
                    }
                    //筛查信息
                    OutsideVo.DetailVo.Record record = map.get("SCWJ-ILLNESS");
                    row += 1;
                    excelWriter.writeCellValue(0, row, detailVos.get(i).getName() + "");
                    excelWriter.writeCellValue(1, row, map.get("SCWJ-SEX") == null ? "" : map.get("SCWJ-SEX").getAnswer());
                    excelWriter.writeCellValue(2, row, map.get("SCWJ-AGE") == null ? "" : map.get("SCWJ-AGE").getAnswer());
                    excelWriter.writeCellValue(3, row, map.get("SCWJ-idCard") == null ? "" : map.get("SCWJ-idCard").getAnswer());
                    excelWriter.writeCellValue(4, row, map.get("SCWJ-BIRTH") == null ? "" : map.get("SCWJ-BIRTH").getAnswer());
                    excelWriter.writeCellValue(5, row, map.get("SCWJ-PHONE") == null ? "" : map.get("SCWJ-PHONE").getAnswer());
                    excelWriter.writeCellValue(6, row, map.get("RZSC-PDL") == null ? "" : map.get("RZSC-PDL").getAnswer());
                    excelWriter.writeCellValue(7, row, map.get("RZSC-XQAH") == null ? "" : map.get("RZSC-XQAH").getAnswer());
                    excelWriter.writeCellValue(8, row, map.get("RZSC-BDCF") == null ? "" : map.get("RZSC-BDCF").getAnswer());
                    excelWriter.writeCellValue(9, row, map.get("RZSC-XXKN") == null ? "" : map.get("RZSC-XXKN").getAnswer());
                    excelWriter.writeCellValue(10, row, map.get("RZSC-JBQ") == null ? "" : map.get("RZSC-JBQ").getAnswer());
                    excelWriter.writeCellValue(11, row, map.get("RZSC-CWKN") == null ? "" : map.get("RZSC-CWKN").getAnswer());
                    excelWriter.writeCellValue(12, row, map.get("RZSC-JBZ") == null ? "" : map.get("RZSC-JBZ").getAnswer());
                    excelWriter.writeCellValue(13, row, map.get("RZSC-RCJY") == null ? "" : map.get("RZSC-RCJY").getAnswer());
                    excelWriter.writeCellValue(14, row, map.get("RZSC-RESULT") == null ? "" : map.get("RZSC-RESULT").getAnswer());
                    excelWriter.writeCellValue(15, row, map.get("SCWJ-SQMC") == null ? "" : map.get("SCWJ-SQMC").getAnswer());
                }
            }
        }

        String filename = StrUtil.format("问卷-{}.xlsx", DateUtil.date().toString("yyyyMMdd"));

        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            excelWriter.flush(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭writer，释放内存
            excelWriter.close();
            //此处记得关闭输出Servlet流
            IoUtil.close(out);
        }
    }
}
